package main.java.indi.zyj.hot100;

public class _69_exist {

    boolean[][] visited = null;

    public boolean exist(char[][] board, String word) {

        visited = new boolean[board.length][board[0].length];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == word.charAt(0)) {
                    if (dfs(i, j, board, word, 0)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(int x, int y, char[][] board, String word, int index) {
        if (index == word.length()) return true;
        if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return false;
        if (visited[x][y]) return false;
        if (board[x][y] != word.charAt(index)) return false;
        visited[x][y] = true;
        boolean res = dfs(x - 1, y, board, word, index + 1) ||
                dfs(x, y - 1, board, word, index + 1) ||
                dfs(x + 1, y, board, word, index + 1) ||
                dfs(x, y + 1, board, word, index + 1);
        visited[x][y] = false;
        return res;
    }
}
